/**
 * 
 */
package com.socialnetwork.user.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.socialnetwork.security.auth.Authenticator;
import com.socialnetwork.security.pwd.PwdAuthenticator;
import com.socialnetwork.user.model.User;

/**
 * @author asoundar
 * 
 */
@Repository
public class UserDAOImpl implements UserDAO {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public void addUser(User user) {
		getCurrentSession().save(user);
	}

	@SuppressWarnings("unchecked")
	public List<User> listUser() {

		return getCurrentSession().createQuery("from User").list();
	}

	public void removeUser(Integer id) {
		User user = (User) sessionFactory.getCurrentSession().load(User.class,
				id);
		if (null != user) {
			getCurrentSession().delete(user);
		}
	}

	@SuppressWarnings("unchecked")
	public User getUser(String email) {
		List<User> userList = new ArrayList<User>();
		Query query = getCurrentSession().createQuery(
				"from User u where u.email = :email");
		query.setParameter("email", email);
		userList = query.list();
		if (userList.size() > 0)
			return userList.get(0);
		else
			return null;
	}
	
	public int authenticateByEmailAddress(String emailAddress, String password) {
		// Get user
		int authResult = Authenticator.FAILURE;
		User user = null;
		
		user = getUser(emailAddress);
		
		boolean authenticated = PwdAuthenticator.authenticate(
				emailAddress, password, user.getPassword());

		if (authenticated) {
			authResult = Authenticator.SUCCESS;
		} else {
			authResult = Authenticator.FAILURE;
		}
		
		return authResult;
	}
	
}
